package jetbrains.buildServer.cuta.web;

import jetbrains.buildServer.configuration.ChangeListener;
import jetbrains.buildServer.configuration.FileWatcher;
import jetbrains.buildServer.cuta.logic.CutaDef;
import jetbrains.buildServer.cuta.logic.CutaMainTab;
import jetbrains.buildServer.cuta.logic.operators.ExternalContext;
import jetbrains.buildServer.web.openapi.PluginDescriptor;
import jetbrains.buildServer.web.openapi.WebControllerManager;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;



/**
 * @author Leonid Bushuev from JetBrains
 */
public class AgentsCustomTableTabFactory
{
    @NotNull
    private final ExternalContext myExtContext;

    @NotNull
    private final WebControllerManager myWCManager;

    @NotNull
    private final CutaDef myCutaDef;

    @NotNull
    private final List<AgentsCustomTableTabPage> myMainPages =
            new ArrayList<AgentsCustomTableTabPage>(2);

    @NotNull
    private final String myIncludeUrl;





    public AgentsCustomTableTabFactory(final @NotNull WebControllerManager wcManager,
                                       final @NotNull PluginDescriptor pluginDescriptor,
                                       final @NotNull ExternalContext extContext,
                                       final @NotNull CutaDef cutaDef)
    {
        myCutaDef = cutaDef;
        myExtContext = extContext;
        myWCManager = wcManager;
        myIncludeUrl = pluginDescriptor.getPluginResourcesPath("cuta-agents-tab.jsp");

        myCutaDef.refreshListeners.add(new ChangeListener()
        {
            public void changeOccured(String requestor) { configurationHasChanged(); }
        });
    }


    public void registerPages()
    {
        String placeAfterTabId = "agentsStatisticsTab";

        for (CutaMainTab mainTab: myCutaDef.tabs.values())
        {
            AgentsCustomTableTabPage mainTabPage =
                    new AgentsCustomTableTabPage(myWCManager, myExtContext, myIncludeUrl, mainTab, placeAfterTabId);
            myMainPages.add(mainTabPage);
            placeAfterTabId = mainTab.getId();
        }
    }


    public void unregisterPages()
    {
        for (int i = myMainPages.size()-1; i >= 0; i--)
        {
            AgentsCustomTableTabPage thePage = myMainPages.get(i);
            thePage.unregister();
        }
    }


    private void configurationHasChanged()
    {
        unregisterPages();
        registerPages();
    }

}
